import logging
import os
import time

import allure
from appium import webdriver
from appium.options.common import AppiumOptions  # 需要使用这种方式传入caps参数

from base.base_page import BasePage


class PanoXv2(BasePage):

    _pilot_apps = {
        'camera_package': 'com.pi.pilot.camera',
        'gallery_package': 'com.pi.pilot.gallery',
        'setting_package': 'com.pi.pilot.setting',
        'interactive_package': 'com.pi.pilot.interactive',
        'ime_package': 'com.pi.pilot.ime',
        'tools_package': 'com.pi.pilot.tools',
        'service_package': 'com.pi.pilot.service',
        'guide_package': 'com.pi.pilot.guide',
        'upgrade_package': 'com.pi.pilot.upgrade',
        'iqtest_package': 'com.pi.pilot.iqtest',
        'browser_package': 'com.pi.pilot.browser',
        'helper_package': 'com.pi.pilot.helper'
    }

    _camera_activity = '.ui.CameraActivity'
    _device_name = ''
    _platformName = 'android'
    _platformVersion = '10.0'

    """
    _udid和_port是多设备参数，用于命令行中测试多台设备
    命令行中输入udid="设备的udid" port=4723 pytest test_xxx.py
    命令行中输入udid="设备的udid" port=4725 pytest test_xxx.py
    注意端口号要隔1个数，例如第一台设备使用的的端口号是4723，第二台设备使用的端口号就用4725
    """
    _udid = os.getenv("udid")
    _port = os.getenv("port")

    """
    初始化app
    进行安装待测app、安装appium服务app、授权、隐式等待等等配置
    """
    def init(self):
        logging.info("初始化app")
        # 判断是否有传入driver，没有就新增，有就复用
        if self.driver is None:
            logging.info(f"driver为'{self.driver}'")
            # 初始化app所需caps

            # 新版appium库需要这样传入caps参数
            options = AppiumOptions()
            options.platform_name = self._platformName
            options.platformVersion = self._platformVersion
            options.appPackage = self._pilot_apps['camera_package']
            options.appActivity = self._camera_activity
            options.noReset = 'true'
            options.autoAcceptAlerts = 'true'
            options.autoGrantPermissions = 'true'

            # 使用caps参数连接appium server
            self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", options=options)
            self.driver.implicitly_wait(5)
            self.driver.update_settings({"waitForIdleTimeout": 0})
            self.open_launcher_app()
            # 如果要测试多台设备则需要通过命令行传入的port和udid进行分配
            # self.driver = webdriver.Remote(f"http://127.0.0.1:{self._port}/wd/hub", caps)
            logging.info(f"新建driver为'{self.driver}'")
        else:
            logging.info(f"复用driver为'{self.driver}'")
            self.open_launcher_app()
        return CameraPage(self.driver)

    # 启动app，根据实际测试情况决定是否清除app数据和设置
    def start(self):
        logging.info("初始化完成，启动app")
        if self.driver is None:
            logging.info(f"driver为'{self.driver}'")

            # 初始化app所需caps
            options = AppiumOptions()
            options.platform_name = self._platformName
            options.platformVersion = self._platformVersion
            options.appPackage = self._pilot_apps['camera_package']
            options.appActivity = self._camera_activity
            options.noReset = 'true'
            options.autoAcceptAlerts = 'true'
            options.skipServerInstallation = 'true'
            options.autoGrantPermissions = 'true'
            options.skipDeviceInstallation = 'true'
            options.waitForIdleTimeout = 10

            # 使用caps参数连接appium server
            self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", options=options)
            self.driver.implicitly_wait(5)
            # 解决appium服务卡住导致找不到元素或点击元素无效的问题，来源https://ceshiren.com/t/topic/17003/4
            self.driver.update_settings({"waitForIdleTimeout": 0})
            self.open_launcher_app()

        else:
            logging.info(f"复用driver为'{self.driver}'")
            self.open_launcher_app()
        return CameraPage(self.driver)

    def open_launcher_app(self):
        self.driver.activate_app(self._pilot_apps['camera_package'])

    def close_launcher_app(self):
        self.driver.terminate_app(self._pilot_apps['camera_package'])

    # 重启app
    def restart_launcher_app(self):
        logging.info("重启首页app")
        self.close_launcher_app()
        self.open_launcher_app()

    # 断开appium连接
    def stop_test(self):
        logging.info("断开appium连接")
        self.driver.quit()
        return self

    # 杀死app，针对caps之外的app
    def kill_app(self, package):
        logging.info(f"杀死app'{package}'")
        os.popen(f"adb shell am force-stop '{package}'")
        return self

    # 杀死pilot app
    def kill_pilot_apps(self):

        for app in self._pilot_apps.values():
            if app == 'com.pi.pilot.service':
                continue
            self.kill_app(app)

    # 清除app数据并关闭app，对caps之外的app生效
    @allure.step("清除app缓存，可以还原app设置")
    def clear_app(self, package):
        logging.info(f"清除app'{package}'缓存")
        os.popen(f"adb shell pm clear '{package}'")
        return self

    def clear_all_app(self, packages=_pilot_apps.values()):
        for package in packages:
            self.clear_app(package)
        return self

    # 截图返回路径
    def screenshot(self):
        base_dir = os.path.dirname(__file__)
        screenshot_dir = os.path.join(base_dir, "..", "data", "screenshot")
        now = time.strftime("%Y-%m-%d_%H-%M-%S")
        screenshot_name = now + ".png"
        screenshot_path = os.path.join(screenshot_dir, screenshot_name)
        self.driver.get_screenshot_as_file(screenshot_path)
        logging.info(f"截图，名为{screenshot_name}")
        return screenshot_path
